package com.amos.stuff.common.service;

import com.amos.stuff.common.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Copyright © 2018 五月工作室. All rights reserved.
 *
 * @Project: stuff
 * @ClassName: EnumConverterFactory
 * @Package: com.amos.stuff.common.service
 * @author: zhuqb
 * @Description:
 * @date: 2019/9/27 0027 上午 10:35
 * @Version: V1.0
 */
public class EnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    private static Map<Class, Converter> convertMap = new ConcurrentHashMap<>();

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> aClass) {
        Converter converter = convertMap.get(aClass);
        if (null == converter) {
            converter = new EnumConverter(aClass);
            convertMap.put(aClass, converter);
        }
        return converter;
    }

    class EnumConverter<T extends BaseEnum> implements Converter<String, T> {

        private Class<T> clazz;
        private Map<String, T> enumMap = new ConcurrentHashMap<>();


        public EnumConverter(Class<T> clazz) {
            this.clazz = clazz;

            T[] enums = clazz.getEnumConstants();
            for (T anEnum : enums) {
                this.enumMap.put(anEnum.getKey(), anEnum);
            }
        }

        @Override
        public T convert(String key) {
            T result = this.enumMap.get(key);

            if (null == result) {
                throw new IllegalArgumentException("params is wrong");
            }

            return result;
        }
    }
}
